package com.cloudwise.controller;

import cn.hutool.core.lang.UUID;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.cloudwise.entity.ReturnBean;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 张燕豪
 * @description
 * @date 2022/1/24
 */
@RestController
@RequestMapping("alipay")
public class PayCodeController extends BaseController{
    private final String APP_ID = "2021000119602938";
    private final String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCAliLwhmFck9KyhhHuvR8mYbuWm+WRjLPrMS3E9NDtKxpGuXrDQsIZCkVt3Ax5Q6ZSXuvj4GBoGofG36uG4SpDNB3Tjp6ypwfg268IZV4Dc0aiJb3UUU1KRUF4vl0tNxNMj4omXaLYfGBNQcAqtD9Ao6U9vRK8WhrKtn6s+ankkf3UKmzhv9uhdllSnYbm550Ui6QHQkZ4RUkJABk/qhTuF97vO717kT/uATffCdyZK5UJZFImg2q02PbT4giMIDjAY9QsMahLTAr+qLEMp8rndvUkfHBe5AMOErVnz4nQKdqTjAYLecNgwApFUXk3kYDeCSGf37vbMMGYr7wjHHPlAgMBAAECggEAe+Ssy4UewB1p8Dq/goDUR535KZcR7VhdbmoXCGM9/pX+HlDOGN70tz2vQbe4iQqGcW0l6Y0iNowBcLvHwBCpMNFBP7p16/qF28Cvd+57U+W5E7g7nBut1ba+64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8ashjrUSxQ==";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgVLh+5OTUCBLzMAsFnY2YVZiJqRqIG+cUKgWSB7Q4YTpWhz4+0U/ho2/Wylj+cxQJPdg0UQPUOzoNfLseeaWGD7XPAaM6XvC+Y1HScx44M/1KjmgtIOkdjtD7ePbg5KooL3BioSXaEresU8A/S2V7/CNM9Udi0go4byyeqjkV0pCAhmHwR9h3O3M2r6I7LVFuk5yKkZlV+i2Sor/E8ARH6mA9NE8+Ms6S2gVm11WkGCwFiNGI7OIlFBnuwgzGT4ZSmbjxa8A8z3teTRf8d8EIZ83wDl48HTlSzI7pyHKJw6dY2IYCfcZB1pvogXpQ4LGyBn48C6I1FvSAN5Qj5xn2QIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/alipay";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://127.0.0.1/success";



    @PostMapping("aliapy")
    public ReturnBean alipay(String name,String amount){
        ReturnBean returnBean =new ReturnBean();
        SecureRandom r= new SecureRandom();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =amount;
        //订单名称，必填
        String subject =name;
        //商品描述，可空
        String body = "欢迎您到AAA学习知识。";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return super.success(true,1L);
//        httpResponse.setContentType("text/html;charset=" + CHARSET);
//        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
//        httpResponse.getWriter().flush();
//        httpResponse.getWriter().close();
    }

    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);
            //支付成功，修复支付状态
            //payService.updateById(Integer.valueOf(out_trade_no));
            return "ok";//跳转付款成功页面
        }else{
            return "no";//跳转付款失败页面
        }

    }
}